package cn.com.nxt.txb.util;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.PorterDuff.Mode;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.nostra13.universalimageloader.core.DisplayImageOptions;

import org.apache.commons.codec.binary.Base64;
import org.json.JSONObject;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.math.BigDecimal;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import cn.com.nxt.txb.model.User;


/**
 * 无需传入Context的工具类
 */
public class AppUtil {
	public static User mUser;
	public static final String SETTING_ISFIRST = "is_first";

	public static String getJoinMeetingParam(String phone,String name,String meetingid,String roomid,int action,int role){
		Map<String, Object> map = new HashMap<>();
		map.put("phone", phone);
		map.put("name", name);
		map.put("meetingid",meetingid);
		map.put("roomid", roomid);
		map.put("action", new Integer(action));
		map.put("role", new Integer(role));
		Gson gson = new Gson();
		return gson.toJson(map);
	}
	/**
	 * 判断是否有网络
	 */
	public static boolean isNetwork(Context ctx) {
		if (ctx == null) {
			return false;
		}
		ConnectivityManager cm = (ConnectivityManager) ctx
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo ni = cm.getActiveNetworkInfo();
		return ni != null && ni.isConnectedOrConnecting();
	}

	/**
	 * 判断是否为数字
	 */
	public static boolean isNumeric(String str) {
		if (str == null || str.isEmpty())
			return false;
		Pattern pattern = Pattern.compile("[0-9]*");
		Matcher isNum = pattern.matcher(str);
		if (!isNum.matches()) {
			return false;
		}
		return true;
	}

	/**
	 * 是否为空
	 */
	public static boolean isBlank(String src) {
		if (src == null)
			return true;
		src = src.trim();
		if (src == null)
			return true;
		if (src.equals(""))
			return true;
		return false;
	}

//	public static boolean isLogin(Context context) {
//		boolean falg = false;
//		SharedPreferences sp = context.getSharedPreferences("USERINFO", 0);
//		if (App.mUserInfo == null) {
//			App.mUserInfo = FileUtil.readUser(context);
//		}
//		App.setDataInfo(App.mUserInfo);
//		if (TextUtils.isEmpty(App.uuid)) {
//			falg = true;
//		} else {
//			App.setDataInfo(App.mUserInfo);
//		}
//		return falg;
//	}

	/**
	 * 固定ListView的高度
	 */
	public static void setListViewHeightBasedOnChildren(ListView listView) {
		ListAdapter listAdapter = listView.getAdapter();
		if (listAdapter == null) {
			return;
		}
		int totalHeight = 0;
		for (int i = 0; i < listAdapter.getCount(); i++) {
			View listItem = listAdapter.getView(i, null, listView);
			listItem.measure(0, 0);
			totalHeight += (listItem.getMeasuredHeight() + 4);
		}
		ViewGroup.LayoutParams params = listView.getLayoutParams();
		params.height = totalHeight
				+ (listView.getDividerHeight() * (listAdapter.getCount() - 1));
		params.height += 10;
		listView.setLayoutParams(params);
	}

	/**
	 * 解析月份，如果月份小于10，前面加0
	 */
	public static String parseMonth(int month) {
		if ((month + 1) < 10) {
			return "0" + (month + 1);
		} else {
			return String.valueOf((month + 1));
		}
	}

	/**
	 * 解析日期，如果日期小于10，前面加0
	 */
	public static String parseDayOfMonth(int day) {
		if (day < 10) {
			return "0" + day;
		} else {
			return String.valueOf(day);
		}
	}

	/**
	 * 传送公共参数用户名、密码及随机码
	 */
	public static JSONObject parm(JSONObject obj) {

		return obj;
	}

	/**
	 * 获得一个UUID
	 */
	public static String getUUID() {
		String s = UUID.randomUUID().toString().toUpperCase()
				.replaceAll("-", "");
		// return (s.substring(0, 8) + s.substring(9, 13) + s.substring(14, 18)+
		// s.substring(19, 23) + s.substring(24)).toUpperCase();
		return s;
	}

	/**
	 * 验证号码 手机号 固话均可
	 */
	public static boolean isPhoneNumberValid(String phoneNumber) {
		boolean isValid = false;
		String expression = "((^(13|15|18|17)[0-9]{9}$)|(^0[1,2]{1}\\d{1}-?\\d{8}$)|(^0[3-9] {1}\\d{2}-?\\d{7,8}$)|(^0[1,2]{1}\\d{1}-?\\d{8}-(\\d{1,4})$)|(^0[3-9]{1}\\d{2}-? \\d{7,8}-(\\d{1,4})$))";
		CharSequence inputStr = phoneNumber;
		Pattern pattern = Pattern.compile(expression);
		Matcher matcher = pattern.matcher(inputStr);
		if (matcher.matches()) {
			isValid = true;
		}
		return isValid;
	}

	/**
	 * 字符串转double类型
	 */
	public static double getConvertDouble(String str) {
		double i = 0;
		try {
			i = Double.parseDouble(str);
		} catch (Exception e) {
			i = 0;
		}

		return i;
	}

	private static Bitmap cutBmp(Bitmap bmp) {
		Bitmap result;
		int w = bmp.getWidth();// ���볤���ο�
		int h = bmp.getHeight();// ���볤���θ�
		int nw;// ������ο�
		if (w > h) {
			// ����ڸ�
			nw = h;
			result = Bitmap.createBitmap(bmp, (w - nw) / 2, 0, nw, nw);
		} else {
			// �ߴ��ڿ�
			nw = w;
			result = Bitmap.createBitmap(bmp, 0, (h - nw) / 2, nw, nw);
		}
		return result;
	}

	public static Bitmap getRoundedCornerBitmap(Bitmap bitmap, float roundPX) {
		Bitmap bmp = cutBmp(bitmap);
		Bitmap output = Bitmap.createBitmap(bmp.getWidth(), bmp.getHeight(),
				Config.ARGB_8888);
		Canvas canvas = new Canvas(output);
		final int color = 0xff424242;
		final Paint paint = new Paint();
		final Rect rect = new Rect(0, 0, bmp.getWidth(), bmp.getHeight());
		final RectF rectF = new RectF(rect);
		paint.setAntiAlias(true);
		canvas.drawARGB(0, 0, 0, 0);
		paint.setColor(color);
		canvas.drawRoundRect(rectF, roundPX, roundPX, paint);
		paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
		canvas.drawBitmap(bmp, rect, rect, paint);
		return output;
	}

	public static Bitmap toRoundBitmap(Bitmap bitmap) {
		int width = bitmap.getWidth();
		int height = bitmap.getHeight();
		float roundPx;
		float left, top, right, bottom, dst_left, dst_top, dst_right, dst_bottom;
		if (width <= height) {
			roundPx = width / 2;
			top = 0;
			bottom = width;
			left = 0;
			right = width;
			height = width;
			dst_left = 0;
			dst_top = 0;
			dst_right = width;
			dst_bottom = width;
		} else {
			roundPx = height / 2;
			float clip = (width - height) / 2;
			left = clip;
			right = width - clip;
			top = 0;
			bottom = height;
			width = height;
			dst_left = 0;
			dst_top = 0;
			dst_right = height;
			dst_bottom = height;
		}
		Bitmap output = Bitmap.createBitmap(width, height, Config.ARGB_8888);
		Canvas canvas = new Canvas(output);
		final int color = 0xff424242;
		final Paint paint = new Paint();
		final Rect src = new Rect((int) left, (int) top, (int) right,
				(int) bottom);
		final Rect dst = new Rect((int) dst_left, (int) dst_top,
				(int) dst_right, (int) dst_bottom);
		final RectF rectF = new RectF(dst);
		paint.setAntiAlias(true);
		canvas.drawARGB(0, 0, 0, 0);
		paint.setColor(color);
		canvas.drawRoundRect(rectF, roundPx, roundPx, paint);
		paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
		canvas.drawBitmap(bitmap, src, dst, paint);
		return output;
	}

	/**
	 * 根据手机的分辨率从 dp 的单位 转成为 px(像素)
	 */
	public static int dp2px(Context context, float dpValue) {
		final float scale = context.getResources().getDisplayMetrics().density;
		return (int) (dpValue * scale + 0.5f);
	}

	/**
	 * 存储用户对象
	 */
	public static void saveUser(Context cxt, User user) {
		SharedPreferences preferences = cxt.getSharedPreferences(AppConstant.USERINFO,
				0);
		// 创建字节输出流
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		try {
			// 创建对象输出流，并封装字节流
			ObjectOutputStream oos = new ObjectOutputStream(baos);
			// 将对象写入字节流
			oos.writeObject(user);
			// 将字节流编码成base64的字符窜
			String user_Base64 = new String(Base64.encodeBase64(baos
					.toByteArray()));
			Editor editor = preferences.edit();
			editor.putString("userinfo", user_Base64);
			editor.commit();
		} catch (IOException e) {
		}
	}
	/**
	 * 清除用户对象
	 */
	public static  void clearUser(Context cxt){
		SharedPreferences preferences = cxt.getSharedPreferences(AppConstant.USERINFO,
				0);
		Editor editor = preferences.edit();
		editor.putString("userinfo", "");
		editor.commit();
	}

	/**
	 * 解析用户信息
	 *
	 * @return
	 */
	public static User readUser(Context cxt) {
		User user_1 = null;
		SharedPreferences preferences = cxt.getSharedPreferences(AppConstant.USERINFO,
				0);
		String productBase64 = preferences.getString("userinfo", "");

		// 读取字节
		byte[] base64 = Base64.decodeBase64(productBase64.getBytes());

		// 封装到字节流
		ByteArrayInputStream bais = new ByteArrayInputStream(base64);
		try {
			// 再次封装
			ObjectInputStream bis = new ObjectInputStream(bais);
			// 读取对象
			user_1 = (User) bis.readObject();
		} catch (Exception e) {
		}
		return user_1;
	}


}
